package org.example.rxJava;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Emitter;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Action1;

public class RxJavaObserverDemo {

    private static final Logger LOGGER = LoggerFactory.getLogger(RxJavaObserverDemo.class);

    @Test
    public void rxJavaBaseUse() {
        // 被观察者（主题）
        Observable observable = Observable.create(new Action1<Emitter<String>>() {
            @Override
            public void call(Emitter<String> emitter) {
                emitter.onNext("apple");
                emitter.onNext("banana");
                emitter.onNext("pear");
                // onNext和onCompleted没有必然的联系
                emitter.onCompleted();
            }
        }, Emitter.BackpressureMode.NONE);

        // 观察者
        Subscriber<String> subscriber = new Subscriber<String>() {
            @Override
            public void onCompleted() {
                LOGGER.info("onCompleted");
            }

            @Override
            public void onError(Throwable throwable) {

            }

            @Override
            public void onNext(String s) {
                LOGGER.info("收到消息：{}", s);
            }
        };

        observable.subscribe(subscriber);
    }

    @Test
    public void rxJavaActionUse() {
        Observable<String> observable = Observable.create(new Action1<Emitter<String>>() {
            @Override
            public void call(Emitter<String> emitter) {
                emitter.onNext("apple");
                emitter.onNext("banana");
                emitter.onNext("pear");
                emitter.onCompleted();
            }
        }, Emitter.BackpressureMode.BUFFER);

        // 函数式编程
        observable.subscribe(s->{
            LOGGER.info("onNext：{}", s);
        }, e->{
            LOGGER.info("收到异常：{}", e.getMessage());
        }, ()->{
            LOGGER.info("方法完成：onCompleted");
        });
    }

    @Test
    public void rxJavaActionLamda() {
        Observable<String> observable = Observable.just("apple", "banana", "pear");
        observable.subscribe(s->{
            LOGGER.info("onNext：{}", s);
        });
    }
}
